import { useContext, useRef, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { AuthContext } from '@/contexts/authContext';
import { Toaster, toast } from 'sonner';
import { Bot, RefreshCw, AlertCircle, CheckCircle } from 'lucide-react';

export default function AgentPage() {
  const { isAuthenticated } = useContext(AuthContext);
  const navigate = useNavigate();
  const iframeRef = useRef<HTMLIFrameElement>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(false);
  const [loadAttempts, setLoadAttempts] = useState(0);
  const maxLoadAttempts = 3;

  // 未登录时重定向到登录页
  useEffect(() => {
    if (!isAuthenticated) {
      navigate('/login');
    }
  }, [isAuthenticated, navigate]);

  // 重新加载iframe
  const handleRefresh = () => {
    setIsLoading(true);
    setError(false);
    
    if (iframeRef.current) {
      // 添加时间戳参数确保完全刷新而不是使用缓存
      const timestamp = new Date().getTime();
      const src = `https://www.coze.cn/store/agent/7561051703118938163?bot_id=true&t=${timestamp}`;
      iframeRef.current.src = src;
      toast('正在重新加载智能助手...');
    }
  };

  // 处理iframe加载完成
  const handleIframeLoad = () => {
    setIsLoading(false);
    setError(false);
    setLoadAttempts(0); // 重置尝试次数
    toast('智能助手加载成功！', { icon: <CheckCircle size={16} /> });
  };

  // 处理iframe加载失败
  const handleIframeError = () => {
    setLoadAttempts(prev => {
      const newAttempts = prev + 1;
      
      if (newAttempts < maxLoadAttempts) {
        // 自动重试
        toast(`加载失败，正在尝试第${newAttempts + 1}次...`);
        setTimeout(() => {
          if (iframeRef.current) {
            const timestamp = new Date().getTime();
            iframeRef.current.src = `https://www.coze.cn/store/agent/7561051703118938163?bot_id=true&t=${timestamp}`;
          }
        }, 1000);
      } else {
        // 达到最大尝试次数，显示错误
        setError(true);
        setIsLoading(false);
        toast('智能助手加载失败，请稍后再试或点击刷新按钮重试', { 
          icon: <AlertCircle size={16} />, 
          className: 'bg-red-50 text-red-700' 
        });
      }
      
      return newAttempts;
    });
  };

   // 组件挂载时设置iframe事件监听和高度调整
  useEffect(() => {
    const iframe = iframeRef.current;
    
    // 添加窗口大小变化时重新调整高度
    const handleResize = () => {
      if (iframeRef.current) {
        // 设置初始高度为视口高度减去顶部和底部导航
        const windowHeight = window.innerHeight;
        const adjustedHeight = windowHeight - 200; // 减去顶部和底部导航栏高度
        iframeRef.current.style.height = `${adjustedHeight}px`;
      }
    };
    
    // 添加窗口调整事件监听
    window.addEventListener('resize', handleResize);
    
    // 初始调整高度
    handleResize();
    
    // 清理函数
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  // 添加超时检测
  useEffect(() => {
    if (isLoading) {
      const timeout = setTimeout(() => {
        if (isLoading) {
          // 超时处理
          setError(true);
          setIsLoading(false);
          toast('加载超时，请检查网络连接或点击刷新按钮重试', { 
            icon: <AlertCircle size={16} />,
            className: 'bg-red-50 text-red-700'
          });
        }
      }, 15000); // 15秒超时
      
      return () => clearTimeout(timeout);
    }
  }, [isLoading]);

  // 未登录时不渲染内容
  if (!isAuthenticated) {
    return null;
  }

  return (
    <div className="min-h-screen bg-gradient-to-b from-pink-50 to-blue-50 flex flex-col pb-20 text-gray-800">
      <div className="container mx-auto flex-1 flex flex-col">
      <Toaster />
      
       {/* 顶部导航栏 - 智能体身份强化 */}
      <header className="bg-white/80 backdrop-blur-md border-b border-pink-100 px-4 py-3 flex justify-between items-center shadow-sm">
        <div className="flex items-center">
           <span className="text-2xl font-bold text-gradient">
              <img 
                src="https://lf-code-agent.coze.cn/obj/x-ai-cn/307173148162/attachment/e7cb1a9e560c13e8924d04f1d807bc45_20251022234653.jpg" 
                alt="童话家" 
                className="w-6 h-6 rounded-full object-cover mr-1" 
              /> 童话家 - 你的AI故事伙伴
          </span>
        </div>
        <button 
          onClick={handleRefresh}
          className="p-2 bg-gradient-to-r from-pink-100 to-blue-100 text-pink-400 rounded-full hover:from-pink-200 hover:to-blue-200 transition-colors"
          aria-label="刷新童话家"
        >
          <RefreshCw size={18} />
        </button>
      </header>

       {/* 智能体介绍 - 强调伙伴身份 */}
      <section className="px-6 pt-4 pb-2">
        <div className="bg-gradient-to-r from-pink-50 to-blue-50 p-3 rounded-lg border border-pink-100 mb-4">
          <p className="text-sm text-pink-500 flex items-center">
            <Bot size={14} className="mr-2" />
            我是你的AI故事伙伴童话家！我可以帮你创造独特的童话故事、给你创作灵感、为故事画插图，还能解答你的各种问题！
          </p>
        </div>
      </section>

       {/* 智能体嵌入区域 */}
      <section className="flex-1 px-6 flex flex-col">
        <div className="flex-1 bg-white rounded-xl border border-pink-100 shadow-sm overflow-hidden relative">
          {/* 显示智能助手内容的iframe */}
          <iframe
            ref={iframeRef}
            id="agent-iframe"
            src="https://www.coze.cn/store/agent/7561051703118938163?bot_id=true"
            title="童话智能助手"
            className="w-full h-full"
            sandbox="allow-forms allow-scripts allow-same-origin allow-popups"
            onLoad={() => {
              // 尝试在iframe加载完成后调整其高度
              if (iframeRef.current && iframeRef.current.contentWindow) {
                try {
                  // 设置初始高度为视口高度减去顶部和底部导航
                  const windowHeight = window.innerHeight;
                  const adjustedHeight = windowHeight - 200; // 减去顶部和底部导航栏高度
                  iframeRef.current.style.height = `${adjustedHeight}px`;
                  
                  // 添加消息监听，用于动态调整高度
                  window.addEventListener('message', (event) => {
                    try {
                      if (event.data && event.data.iframeHeight) {
                        iframeRef.current!.style.height = `${event.data.iframeHeight}px`;
                      }
                    } catch (e) {
                      console.log('Failed to adjust iframe height from message:', e);
                    }
                  });
                  
                  // 尝试通知iframe发送高度信息
                  if (iframeRef.current.contentWindow.postMessage) {
                    iframeRef.current.contentWindow.postMessage(
                      { type: 'requestHeight' },
                      'https://www.coze.cn'
                    );
                  }
                } catch (e) {
                  console.log('Failed to adjust iframe height:', e);
                }
              }
              handleIframeLoad();
            }}
            onError={handleIframeError}
          />
          
          {/* 加载状态指示器 */}
          {(isLoading || error) && (
            <div className="absolute inset-0 flex items-center justify-center bg-white/90 backdrop-blur-sm z-10 p-6">
              <div className="text-center max-w-xs">
                {isLoading ? (
                  <>
                    <div className="animate-spin text-pink-400 mb-3">
                      <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                        <path d="M12 3v3a6 6 0 0 1 6 6v12" />
                      </svg>
                    </div>
                    <h3 className="text-lg font-medium text-gray-800 mb-2">正在加载智能助手...</h3>
                    <p className="text-sm text-gray-500 mb-4">
                      这可能需要几秒钟时间，请稍候
                    </p>
                    <button 
                      onClick={handleRefresh}
                      className="inline-flex items-center text-sm text-pink-500 hover:text-pink-400 transition-colors"
                    >
                      <RefreshCw size={14} className="mr-1" />
                      点击刷新以加快加载
                    </button>
                  </>
                ) : (
                  // 错误状态
                  <>
                    <div className="text-red-400 mb-3">
                      <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                        <path d="M18 6 6 18" />
                        <path d="m6 6 12 12" />
                      </svg>
                    </div>
                    <h3 className="text-lg font-medium text-gray-800 mb-2">智能助手加载失败</h3>
                    <p className="text-sm text-gray-500 mb-4">
                      可能是网络问题或服务暂时不可用，请尝试刷新页面或稍后再试
                    </p>
                     <button 
                      onClick={handleRefresh}
                      className="bg-gradient-to-r from-pink-500 to-blue-500 text-white font-medium py-2 px-4 rounded-lg hover:opacity-90 transition-all duration-300 flex items-center justify-center"
                    >
                      <RefreshCw size={16} className="mr-2" />
                      重新加载智能助手
                    </button>
                  </>
                )}
              </div>
            </div>
          )}
        </div>
      </section>

      {/* 底部导航栏 */}
      <nav className="fixed bottom-0 left-0 right-0 bg-white/90 backdrop-blur-md border-t border-pink-100 h-16 flex justify-around items-center z-10 shadow-sm">
        <button onClick={() => navigate('/home')} className="flex flex-col items-center justify-center text-gray-500 hover:text-pink-500 transition-colors">
          <span className="text-xl">🏠</span>
          <span className="text-xs mt-1">首页</span>
        </button>
        <button onClick={() => navigate('/generate')} className="flex flex-col items-center justify-center text-gray-500 hover:text-pink-500 transition-colors">
          <span className="text-xl">✨</span>
          <span className="text-xs mt-1">生成</span>
        </button>
        <button onClick={() => navigate('/collection')} className="flex flex-col items-center justify-center text-gray-500 hover:text-pink-500 transition-colors">
          <span className="text-xl">❤️</span>
          <span className="text-xs mt-1">收藏</span>
        </button>
        <button onClick={() => navigate('/agent')} className="flex flex-col items-center justify-center text-pink-500">
          <span className="text-xl">🤖</span>
          <span className="text-xs mt-1">智能助手</span>
        </button>
      </nav>
      </div>
    </div>
  );
}